<!-- 我的攻略组件 -->
<template>
  <div class="guide-view">
    <!-- 顶部控制区 -->
    <div class="guide-controls">
      <div class="guide-search">
        <el-input
            v-model="searchQuery"
            placeholder="搜索我的攻略"
            prefix-icon="Search"
            clearable
            @input="handleSearch"
        />
      </div>
      <div class="guide-filters">
        <el-select v-model="filterCategory" placeholder="分类" @change="handleFilterChange">
          <el-option label="全部分类" value="" />
          <el-option label="游戏攻略" value="game" />
          <el-option label="旅游攻略" value="travel" />
          <el-option label="生活攻略" value="life" />
          <el-option label="学习攻略" value="study" />
          <el-option label="其他" value="other" />
        </el-select>
        <el-select v-model="sortOption" placeholder="排序" @change="handleSortChange">
          <el-option label="最新发布" value="newest" />
          <el-option label="最早发布" value="oldest" />
          <el-option label="最多浏览" value="most_viewed" />
          <el-option label="最多点赞" value="most_liked" />
        </el-select>
      </div>
      <el-button type="primary" @click="createNewGuide">
        <el-icon><Plus /></el-icon>发布攻略
      </el-button>
    </div>

    <!-- 攻略列表 -->
    <div v-if="guides.length > 0" class="guide-list">
      <div v-for="guide in guides" :key="guide.id" class="guide-card">
        <div class="guide-card-content">
          <div class="guide-image" v-if="guide.coverImage">
            <img :src="guide.coverImage" :alt="guide.title" />
            <div class="guide-category" :class="getCategoryClass(guide.category)">
              {{ getCategoryName(guide.category) }}
            </div>
          </div>
          <div class="guide-info">
            <h3 class="guide-title" @click="viewGuide(guide)">{{ guide.title }}</h3>
            <p class="guide-description">{{ guide.description }}</p>
            <div class="guide-meta">
              <span class="guide-date">
                <el-icon><Calendar /></el-icon>
                {{ formatDate(guide.createdAt) }}
              </span>
              <span class="guide-views">
                <el-icon><View /></el-icon>
                {{ guide.views }}
              </span>
              <span class="guide-likes">
                <el-icon><Star /></el-icon>
                {{ guide.likes }}
              </span>
            </div>
          </div>
        </div>
        <div class="guide-actions">
          <el-button size="small" type="primary" text @click="viewGuide(guide)">
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button size="small" type="primary" text @click="editGuide(guide)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button size="small" type="danger" text @click="confirmDelete(guide)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="guide-empty">
      <el-empty description="暂无攻略内容">
        <el-button type="primary" @click="createNewGuide">立即发布攻略</el-button>
      </el-empty>
    </div>

    <!-- 分页 -->
    <div class="guide-pagination" v-if="total > pageSize">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="30%"
        :before-close="handleClose"
    >
      <span>确定要删除"{{ selectedGuide.title }}"吗？此操作不可恢复。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteGuide">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'; // 引入useStore
import axios from 'axios'; // 需要引入axios
import {
  Search,
  Plus,
  View,
  Edit,
  Delete,
  Calendar,
  Star
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {getByUserId} from "@/api/travelguide";

export default {
  name: 'GuideView',
  setup() {
    const router = useRouter();
    const store = useStore();

    // 搜索和筛选状态
    const searchQuery = ref('');
    const filterCategory = ref('');
    const sortOption = ref('newest');

    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(5);
    const total = ref(0);

    // 删除对话框
    const deleteDialogVisible = ref(false);
    const selectedGuide = ref({});

    // 攻略数据
    const guides = ref([]);
    const loading = ref(false);

    // 获取分类名称
    const getCategoryName = (category) => {
      const categoryMap = {
        'game': '游戏攻略',
        'travel': '旅游攻略',
        'life': '生活攻略',
        'study': '学习攻略',
        'other': '其他'
      };
      return categoryMap[category] || '其他';
    };

    // 获取分类样式
    const getCategoryClass = (category) => {
      return `category-${category}`;
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      // 如果是标准ISO格式的日期字符串，则转换一下格式
      if (dateString.includes('T')) {
        return dateString.split('T')[0];
      }
      return dateString;
    };

    // 加载攻略数据
    // 加载攻略数据
    const loadGuides = async () => {
      loading.value = true;
      try {
        // 从store获取用户ID
        const userId = store.state.userInfo?.userId;

        // 调用api获取用户攻略数据
        const response = await getByUserId(userId, {
          params: {
            category: filterCategory.value,
            sort: sortOption.value,
            keyword: searchQuery.value,
            page: currentPage.value,
            size: pageSize.value
          }
        });

        // 处理返回的数据
        if (response && response.data) {
          // 转换后端返回的数据结构为前端组件所需的数据结构
          guides.value = response.data.map(guide => ({
            id: guide.guideId,                    // 攻略ID
            title: guide.title,                   // 标题
            description: guide.destination,       // 使用目的地作为描述
            category: guide.tags[0], // 从标签推断分类
            coverImage: guide.coverImage || '/images/default-guide.jpg', // 封面图
            createdAt: guide.createTime,          // 创建时间
            views: guide.viewCount,               // 浏览量
            likes: guide.likeCount                // 点赞数
          }));

          // 更新总记录数用于分页
          total.value = response.data.length;
        } else {
          ElMessage.error('加载攻略失败: 返回数据格式不正确');
        }
      } catch (error) {
        console.error('加载攻略失败:', error);
        ElMessage.error('加载攻略失败: ' + (error.response?.data?.msg || error.message));
      } finally {
        loading.value = false;
      }
    };

// 从标签中推断攻略分类


    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1;
      loadGuides();
    };

    // 筛选变化处理
    const handleFilterChange = () => {
      currentPage.value = 1;
      loadGuides();
    };

    // 排序变化处理
    const handleSortChange = () => {
      currentPage.value = 1;
      loadGuides();
    };

    // 分页变化
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      loadGuides();
    };

    // 创建新攻略
    const createNewGuide = () => {
      router.push('/api/guide/create');
    };

    // 查看攻略详情
    const viewGuide = (guide) => {
      router.push({
        path: '/travelGuidePage',
        query: { id: guide.id }
      });
    };

    // 编辑攻略
    const editGuide = (guide) => {
      router.push(`/api/guide/edit/${guide.id}`);
    };

    // 确认删除
    const confirmDelete = (guide) => {
      selectedGuide.value = guide;
      deleteDialogVisible.value = true;
    };

    // 删除攻略
    const deleteGuide = async () => {
      try {
        const response = await axios.delete(`/api/travel-guide/delete/${selectedGuide.value.id}`);
        if (response.data.code === 200) {
          ElMessage({
            type: 'success',
            message: `攻略"${selectedGuide.value.title}"已成功删除`
          });
          // 重新加载数据
          loadGuides();
        } else {
          ElMessage.error(response.data.msg || '删除攻略失败');
        }
      } catch (error) {
        console.error('删除攻略失败:', error);
        ElMessage.error('删除攻略失败: ' + (error.response?.data?.msg || error.message));
      } finally {
        deleteDialogVisible.value = false;
      }
    };

    // 对话框关闭处理
    const handleClose = () => {
      deleteDialogVisible.value = false;
    };

    // 组件挂载后加载数据
    onMounted(() => {
      loadGuides();
    });

    return {
      searchQuery,
      filterCategory,
      sortOption,
      guides,
      currentPage,
      pageSize,
      total,
      loading,
      deleteDialogVisible,
      selectedGuide,
      handleSearch,
      handleFilterChange,
      handleSortChange,
      handleCurrentChange,
      createNewGuide,
      viewGuide,
      editGuide,
      confirmDelete,
      deleteGuide,
      handleClose,
      getCategoryName,
      getCategoryClass,
      formatDate
    };
  }
};
</script>

<style scoped>
.guide-view {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.guide-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.guide-search {
  flex: 1;
  min-width: 200px;
}

.guide-filters {
  display: flex;
  gap: 10px;
}

.guide-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.guide-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.guide-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.guide-card-content {
  display: flex;
  padding: 16px;
}

.guide-image {
  width: 180px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  position: relative;
  flex-shrink: 0;
}

.guide-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.guide-card:hover .guide-image img {
  transform: scale(1.05);
}

.guide-category {
  position: absolute;
  top: 8px;
  left: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
}

.category-game {
  background-color: rgba(64, 158, 255, 0.8);
}

.category-travel {
  background-color: rgba(103, 194, 58, 0.8);
}

.category-life {
  background-color: rgba(230, 162, 60, 0.8);
}

.category-study {
  background-color: rgba(144, 147, 153, 0.8);
}

.guide-info {
  flex: 1;
  padding-left: 16px;
  display: flex;
  flex-direction: column;
}

.guide-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  cursor: pointer;
  transition: color 0.2s ease;
}

.guide-title:hover {
  color: #00a1d6;
}

.guide-description {
  margin: 0 0 10px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.guide-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: auto;
  font-size: 13px;
  color: #999;
}

.guide-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.guide-meta .el-icon {
  font-size: 14px;
}

.guide-actions {
  display: flex;
  justify-content: flex-end;
  padding: 12px 16px;
  border-top: 1px solid #f5f5f5;
  background-color: #fafafa;
}

.guide-empty {
  padding: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.guide-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .guide-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .guide-filters {
    flex-wrap: wrap;
  }

  .guide-card-content {
    flex-direction: column;
  }

  .guide-image {
    width: 100%;
    height: 180px;
    margin-bottom: 12px;
  }

  .guide-info {
    padding-left: 0;
  }
}
</style>